package com.parse.tree.parsers.service.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.commons.ParsingResult;
import com.commons.ParsingService;


public class JavaParsingService implements ParsingService{

	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
	Map<String, ParsingResult> parsingResults = new HashMap<String, ParsingResult>();

	public Map<String, ParsingResult> parseDirectory(String dirName) throws Throwable {
		List<String> listFilesAndFilesSubDirectories = new ArrayList<String>();
		FileUtil.listFilesAndFilesSubDirectories(listFilesAndFilesSubDirectories,dirName);
		if (listFilesAndFilesSubDirectories == null
				|| listFilesAndFilesSubDirectories.isEmpty())
			return null;
		int size = listFilesAndFilesSubDirectories.size();
		Map<String,Future<ParsingResult>> taskList = new HashMap<String,Future<ParsingResult>>();
		CountDownLatch countDownLatch = new CountDownLatch(size);
		for (String file : listFilesAndFilesSubDirectories) {
			System.out.println("Parsing: " + file);
			CustomJavaParser customParser = new CustomJavaParser(file,
					countDownLatch);
			taskList.put(file, fixedThreadPool.submit(customParser));
		}
		countDownLatch.await();
		Set<Entry<String, Future<ParsingResult>>> taskEntrySet = taskList.entrySet();
		for(Entry<String, Future<ParsingResult>> task : taskEntrySet){
			Future<ParsingResult> result = task.getValue();
			parsingResults.put(task.getKey(),result.get());
		}
		fixedThreadPool.shutdown();
		return parsingResults;

	}

}
